

import java.util.*;
import java.io.*;


public class FileCatalogLoader implements CatalogLoader {
    private Product readProduct(String line) throws DataFormatException {
        StringTokenizer a = new StringTokenizer(line, "_");
        if (a.countTokens() != 4) {
            throw new DataFormatException(line);
        } else {
            try {
                String str1 = a.nextToken();
                return new Product(a.nextToken(), a.nextToken(), Double.parseDouble(a.nextToken()));
            } catch (NumberFormatException num) {
                throw new DataFormatException(line);
            }
        }
    }

    private Coffee readCoffee(String line) throws DataFormatException {
        StringTokenizer b = new StringTokenizer(line, "_");
        if (b.countTokens() != 10)
    {
            throw new DataFormatException(line);
        } else {
            try {
                String str2 = b.nextToken();
                return new Coffee(b.nextToken(), b.nextToken(), Double.parseDouble(b.nextToken()), b.nextToken(), b.nextToken(), b.nextToken(), b.nextToken(), b.nextToken(), b.nextToken());
            } catch (NumberFormatException num) {
                throw new DataFormatException(line);
            }
        }
    }

    private CoffeeBrewer readCoffeeBrewer(String line) throws DataFormatException {
        StringTokenizer c = new StringTokenizer(line, "_");
        if (c.countTokens() != 7) {
            throw new DataFormatException(line);
        } else {
            try {
                String str3 = c.nextToken();
                return new CoffeeBrewer(c.nextToken(), c.nextToken(), Double.parseDouble(c.nextToken()), c.nextToken(), c.nextToken(), Integer.parseInt(c.nextToken()));
            } catch (NumberFormatException num) {
                throw new DataFormatException(line);
            }
        }
    }

    public Catalog loadCatalog(String filename) throws FileNotFoundException, IOException, DataFormatException {
        Catalog cata = new Catalog();
        FileReader file = new FileReader(filename);
        BufferedReader a = new BufferedReader(file);
        String line;
      
        while ((line=a.readLine()) != null) {
            Object obj;
            if (line.startsWith("Coffee")) {
                obj = this.readCoffee(line);
            } else if (line.startsWith("Brewer")) {
                obj = this.readCoffeeBrewer(line);
            } else {
                if(!line.startsWith("Product")) {
                    throw new DataFormatException(line);
                }
                    obj = this.readProduct(line);
                }
                cata.addProduct((Product) obj);
            }
            a.close();
        file.close();
        return cata;
        }

    }


